<template>
  <div class="dept-container">
    <!-- 搜索区域 -->
    <div class="search-form">
      <el-form :inline="false" :model="searchForm" class="demo-form-inline">
        <div style="display: flex; justify-content: space-between; align-items: center; width: 100%;">
          <div style="display: flex; align-items: center;">
            <el-form-item label="部门名称" style="margin-bottom: 0; margin-right: 20px;">
              <el-input v-model="searchForm.name" placeholder="请输入部门名称" style="width: 200px;" />
            </el-form-item>
            <el-form-item label="状态" style="margin-bottom: 0;">
              <el-select v-model="searchForm.status" placeholder="请选择状态" style="width: 150px;">
                <el-option label="正常" value="1" />
                <el-option label="停用" value="0" />
              </el-select>
            </el-form-item>
          </div>
          <el-form-item style="margin-bottom: 0;">
            <el-button type="primary" @click="handleQuery">搜索</el-button>
            <el-button @click="handleReset">清空</el-button>
          </el-form-item>
        </div>
      </el-form>
      <div style="margin-top: 10px;">
        <el-button type="primary" @click="handleAdd">添加部门</el-button>
      </div>
    </div>

    <!-- 数据展示区域 -->
    <div class="data-table">
      <el-table
        v-loading="loading"
        :data="deptList"
        style="width: 100%"
        border
      >
        <el-table-column type="index" label="序号" width="80" :index="indexMethod" />
        <el-table-column prop="name" label="部门名称" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="scope">
            <span :class="getStatusCodeClass(scope.row.status)">{{ formatStatus(scope.row.status) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="updateTime" label="最后修改时间" width="180">
          <template #default="scope">
            {{ formatDateTime(scope.row.updateTime) }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="150" fixed="right">
          <template #default="scope">
            <el-button type="primary" link @click="handleEdit(scope.row)">修改</el-button>
            <el-button type="danger" link @click="handleDelete(scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页组件 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, prev, pager, next, jumper, sizes"
          :total="pagination.total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 部门表单对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="formTitle"
      width="500px"
      :before-close="handleCancel"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="部门名称" prop="name">
          <el-input v-model="formData.name" placeholder="请输入部门名称" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="formData.status" placeholder="请选择状态">
            <el-option label="正常" value="1" />
            <el-option label="停用" value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="handleCancel">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  queryPageApi,
  addApi,
  updateApi,
  deleteApi,
  queryByIdApi,
} from "@/api/dept.js";

// 搜索条件
const searchForm = reactive({
  name: "",
  status: "",
});

// 部门列表数据
const deptList = ref([]);
const loading = ref(false);

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0,
});

// 对话框相关
const dialogVisible = ref(false);
const formTitle = ref("");
const formRef = ref(null);
const isEdit = ref(false);

// 表单数据 - 使用reactive，更适合表单场景
const formData = reactive({
  id: "",
  name: "",
  status: "1",
});

// 表单验证规则
const rules = {
  name: [
    { required: true, message: "请输入部门名称", trigger: "blur" },
    { min: 1, max: 50, message: "长度在 1 到 50 个字符", trigger: "blur" },
  ],
  status: [{ required: true, message: "请选择状态", trigger: "change" }],
};

// 获取部门列表
const getDeptList = async () => {
  try {
    loading.value = true;

    // 构造分页查询参数
    const params = {
      page: pagination.currentPage,
      size: pagination.pageSize,
      ...searchForm, // 包含搜索条件
    };

    console.log("分页查询参数:", params);

    const response = await queryPageApi(params);
    console.log("API响应:", response);

    if (response) {
      // 场景1：后端返回格式 {records: [], total: 0}
      if (response.records !== undefined) {
        deptList.value = response.records || [];
        pagination.total = response.total || 0;
        console.log(
          "处理格式1：当前页",
          deptList.value.length,
          "条，总计",
          pagination.total,
          "条"
        );
      }
      // 场景2：后端返回格式 {rows: [], total: 0}
      else if (response.rows !== undefined) {
        deptList.value = response.rows || [];
        pagination.total = response.total || 0;
        console.log(
          "处理格式2：当前页",
          deptList.value.length,
          "条，总计",
          pagination.total,
          "条"
        );
      }
      // 场景3：后端返回嵌套格式 {data: {records: [], total: 0}} 或 {data: {rows: [], total: 0}}
      else if (response.data) {
        deptList.value = response.data.records || response.data.rows || [];
        pagination.total = response.data.total || 0;
        console.log(
          "处理格式3：当前页",
          deptList.value.length,
          "条，总计",
          pagination.total,
          "条"
        );
      }
      // 场景4：直接返回数组（无分页）
      else if (Array.isArray(response)) {
        deptList.value = response;
        pagination.total = response.length;
        console.log("处理格式4：直接数组，共", pagination.total, "条");
      }
      // 降级处理
      else {
        deptList.value = [];
        pagination.total = 0;
        console.warn("未识别的API返回格式:", response);
      }

      // 特别提示：如果总条数大于当前页显示的条数，用户需要通过分页查看更多数据
      if (pagination.total > pagination.pageSize) {
        console.log(
          `注意：共有${pagination.total}条数据，当前仅显示第${pagination.currentPage}页的${deptList.value.length}条数据，请使用分页功能查看更多。`
        );
      }
    } else {
      // 降级处理，确保页面正常显示
      deptList.value = [];
      pagination.total = 0;
      console.warn("API返回为空:", response);
    }
  } catch (error) {
    ElMessage.error("获取部门列表失败");
    console.error("获取部门列表失败:", error);
    // 错误时也清空数据，避免显示旧数据
    deptList.value = [];
    pagination.total = 0;
  } finally {
    loading.value = false;
  }
};

// 查询
const handleQuery = () => {
  pagination.currentPage = 1;
  getDeptList();
};

// 清空
const handleReset = () => {
  searchForm.name = "";
  searchForm.status = "";
  pagination.currentPage = 1;
  getDeptList();
};

// 添加部门
const handleAdd = () => {
  // 先关闭之前可能存在的对话框
  dialogVisible.value = false;
  
  // 使用setTimeout确保对话框完全关闭后再进行后续操作
  setTimeout(() => {
    // 设置为新增模式
    isEdit.value = false;
    formTitle.value = "新增部门";

    // 强制重置表单数据
    Object.assign(formData, {
      id: "",
      name: "",
      status: "1"
    });

    // 重置表单验证
    if (formRef.value) {
      formRef.value.resetFields();
    }

    // 打开对话框
    dialogVisible.value = true;
  }, 100);
};

// 修改部门
const handleEdit = async (row) => {
  try {
    console.log("开始编辑部门，ID:", row.id);

    // 先关闭之前可能存在的对话框
    dialogVisible.value = false;
    
    // 使用setTimeout确保对话框完全关闭后再进行后续操作
    setTimeout(async () => {
      // 设置编辑状态
      isEdit.value = true;
      formTitle.value = "修改部门";

      // 显示加载状态
      loading.value = true;

      try {
        // 直接使用传入的row数据，避免API调用可能带来的缓存问题
        // 强制重置表单数据
        Object.assign(formData, {
          id: row.id,
          name: row.name || "",
          status: typeof row.status === 'number' ? row.status.toString() : (row.status || "1")
        });

        console.log("填充的表单数据:", formData);

        // 等待DOM更新完成
        await nextTick();

        // 打开对话框
        dialogVisible.value = true;

        // 等待对话框完全打开后重置验证状态
        await nextTick();
        if (formRef.value) {
          // 先清空验证，再重置字段
          formRef.value.clearValidate();
          formRef.value.resetFields();
          
          // 重新设置值，确保数据正确绑定
          Object.assign(formData, {
            id: row.id,
            name: row.name || "",
            status: typeof row.status === 'number' ? row.status.toString() : (row.status || "1")
          });
        }

        console.log("部门编辑对话框已成功打开");
      } catch (innerError) {
        console.error("编辑部门过程中出错:", innerError);
        ElMessage.error("编辑部门失败，请重试");
      } finally {
        loading.value = false;
      }
    }, 100);
  } catch (error) {
    console.error("编辑部门失败:", error);
    ElMessage.error("获取部门信息失败，请重试");
    loading.value = false;
  }
};

// 删除部门
const handleDelete = (row) => {
  ElMessageBox.confirm(`确定要删除部门"${row.name}"吗？`, "确认删除", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  })
    .then(async () => {
      try {
        loading.value = true;
        const response = await deleteApi(row.id);
        console.log("删除响应:", response);

        // 检查删除是否成功 - 增强判断条件，确保能正确识别后端返回的成功状态
        const isSuccess =
          response === true ||
          response?.success === true ||
          response?.code === 200 ||
          response?.code === "200" ||
          response?.status === 200 ||
          response?.code === 1 || // 可能的成功码
          response?.status === "success" ||
          (response && !response.error); // 如果有响应且没有error字段

        console.log('删除响应判断:', { response, isSuccess });

        if (isSuccess) {
          ElMessage.success(response?.message || "删除成功");
          getDeptList(); // 重新获取列表数据
        } else {
          ElMessage.error(response?.message || "删除失败");
        }
      } catch (error) {
        ElMessage.error("删除失败");
        console.error("删除部门失败:", error);
      } finally {
        loading.value = false;
      }
    })
    .catch(() => {
      // 用户取消删除
    });
};

// 分页变化
const handleSizeChange = (size) => {
  pagination.pageSize = size;
  pagination.currentPage = 1; // 重置到第一页
  getDeptList();
};

const handleCurrentChange = (current) => {
  pagination.currentPage = current;
  getDeptList();
};

// 格式化状态显示
const formatStatus = (status) => {
  return status === 1 || status === "1" || status === "normal"
    ? "正常"
    : "停用";
};

// 获取状态样式类名
const getStatusCodeClass = (status) => {
  return status === 1 || status === "1" || status === "normal" ? 'status-normal' : 'status-disabled';
};

// 序号计算方法
const indexMethod = (index) => {
  return (pagination.currentPage - 1) * pagination.pageSize + index + 1;
};

// 格式化日期时间
const formatDateTime = (dateTime) => {
  if (!dateTime) return '';
  // 如果是字符串格式，直接返回
  if (typeof dateTime === 'string') {
    return dateTime;
  }
  // 如果是日期对象，格式化输出
  if (dateTime instanceof Date) {
    return dateTime.toLocaleString();
  }
  // 其他情况返回原始值
  return String(dateTime);
};

// 表单提交处理
const handleSubmit = async () => {
  try {
    // 表单验证
    await formRef.value.validate();

    loading.value = true;

    // 准备提交的数据
    const submitData = {
      name: formData.name,
      status: formData.status
    };

    // 如果是编辑模式，添加id
    if (isEdit.value) {
      submitData.id = formData.id;
    }

    console.log("提交的数据:", submitData);

    let response;
    if (isEdit.value) {
      // 修改
      response = await updateApi(submitData);
    } else {
      // 新增
      response = await addApi(submitData);
    }

    console.log("提交响应:", response);

    // 检查操作是否成功 - 增强判断条件，确保能正确识别后端返回的成功状态
    const isSuccess =
      response === true ||
      response?.success === true ||
      response?.code === 200 ||
      response?.code === "200" ||
      response?.status === 200 ||
      response?.code === 1 || // 可能的成功码
      response?.status === "success" ||
      (response && !response.error); // 如果有响应且没有error字段

    console.log('新增部门响应判断:', { response, isSuccess });

    if (isSuccess) {
      ElMessage.success(
        response?.message || (isEdit.value ? "修改成功" : "添加成功")
      );
      
      // 成功后关闭对话框并重置表单
      dialogVisible.value = false;
      setTimeout(() => {
        if (formRef.value) {
          formRef.value.resetFields();
        }
        Object.assign(formData, {
          id: "",
          name: "",
          status: "1"
        });
      }, 100);
      
      getDeptList(); // 重新获取列表
    } else {
      ElMessage.error(
        response?.message || (isEdit.value ? "修改失败" : "添加失败")
      );
    }
  } catch (error) {
    console.error("提交失败:", error);
    ElMessage.error(isEdit.value ? "修改失败" : "添加失败");
  } finally {
    loading.value = false;
  }
};

// 取消操作
const handleCancel = () => {
  dialogVisible.value = false;
  // 延迟重置表单，确保对话框完全关闭
  setTimeout(() => {
    if (formRef.value) {
      formRef.value.resetFields();
    }
    // 强制重置表单数据
    Object.assign(formData, {
      id: "",
      name: "",
      status: "1"
    });
  }, 100);
};

// 页面加载时获取数据
onMounted(() => {
  getDeptList();
});
</script>

<style scoped>
.dept-container {
  padding: 20px;
}

.search-form {
    margin-bottom: 20px;
    background: #fff;
    padding: 15px;
    border-radius: 4px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  }

  .form-row {
    display: flex;
    align-items: center;
    margin-bottom: 10px;
  }

  .form-actions {
    display: flex;
    justify-content: flex-end;
  }

.data-table {
  margin-bottom: 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  overflow: hidden;
}

.pagination {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 10px;
  padding: 15px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.status-normal {
  color: #67c23a;
  font-weight: 500;
}

.status-disabled {
  color: #f56c6c;
  font-weight: 500;
}
</style>
